package org.db2.project.airline.utils;

import org.db2.project.airline.model.Airport;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 *
 */
public class HibernateHelper {

    private static SessionFactory sessionFactory;

    private HibernateHelper() {
        // empty constructor
    }

    public static void buildSessionFactory() {

        sessionFactory = new AnnotationConfiguration()
                .configure()
                .buildSessionFactory();
    }

    public static void closeSessionFactory() {

        if (sessionFactory != null) {

            sessionFactory.close();
        }
    }

    public static SessionFactory getSessionFactory() {

        if (sessionFactory == null) {
            buildSessionFactory();
        }

        return sessionFactory;
    }

    public static void beginTransaction() {

        sessionFactory.getCurrentSession().beginTransaction();
    }

    public static void rollbackTransaction() {

        sessionFactory.getCurrentSession().getTransaction().rollback();
    }

    public static void commitTransaction() {

        sessionFactory.getCurrentSession().getTransaction().commit();
    }

    private static void openConnection() {
        beginTransaction();
        sessionFactory.getCurrentSession().get(Airport.class, 1l);
        commitTransaction();
    }
}
